package com.happyass.dao;

import com.happyass.pojo.Staff;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface StaffDao extends PagingAndSortingRepository<Staff,Integer>, JpaRepository<Staff,Integer> {
    //根据用户名查找员工信息
    Staff findByStaffUsername(@Param("staffUsername") String staffUsername);

    //根据用户名和密码查找员工信息
    Staff findByStaffUsernameAndStaffPwd(@Param("staffUsername") String staffUsername, @Param("staffPwd") String staffPwd);

    //查询所有用户
    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value="select * from staff order by staff_id",nativeQuery = true)
    List<Staff> getStaffInfos();

    @Transactional
    @Query(nativeQuery = true, value = "select DISTINCT(re.permission) from role r,role_resource_rel rr,staff s,staff_role_rel sr, resource re where re.resource_id = rr.resource_id and r.role_id = rr.role_id and s.staff_id = sr.staff_id and r.role_id = sr.role_id and s.staff_username = :staffUserName")
    List<String> searchPermission(@Param("staffUserName") String staffUserName);

    @Transactional
    @Query(nativeQuery = true,value = "select DISTINCT(r.role_name) from role r, staff s,staff_role_rel sr where r.role_id = sr.role_id and s.staff_id = sr.staff_id and s.staff_username = :staffUserName")
    List<String> searchRole(@Param("staffUserName") String staffUserName);

    @Transactional
    @Query(nativeQuery = true,value = "select s.staff_id,s.staff_name,s.staff_username,s.staff_addr,s.staff_pwd,s.staff_tel,r.role_id,r.role_name from staff s join staff_role_rel sr on s.staff_id = sr.staff_id left join role r on sr.role_id = r.role_id")
    List<Staff> staffRoles();

    @Transactional
    @Query(nativeQuery = true,value = " select s.staff_id,s.staff_name,s.staff_username,s.staff_addr,s.staff_pwd,s.staff_tel,r.role_id,r.role_name from staff s join staff_role_rel sr on s.staff_id = sr.staff_id inner join role r on sr.role_id = r.role_id and s.staff_id = :staffId ")
    Staff selectStaffRolesByStaffId(@Param("staffId") Integer staffId);

}
